package com.mx.app.flatlaf.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.util.List;
import java.util.Random;

public class TableUtil {

    public static JTable addTable(JFrame frame){
        // Table setup
        String[] columnNames = {"工号", "姓名", "集团编码", "工号ID", "网点名称", "销售点编码"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable table = new JTable(tableModel);

        // Generate random data
        addData(tableModel);

        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        return table;
    }
    private static void generateRandomData(DefaultTableModel tableModel) {
        Random random = new Random();
        String[] names = {"张三", "李四", "王五", "赵六", "陈七"};
        String[] outlets = {"北京网点", "上海网点", "广州网点", "深圳网点"};
        String[] salesPoints = {"销售点A", "销售点B", "销售点C", "销售点D"};

        for (int i = 0; i < 20; i++) {
            Object[] rowData = {
                    "工号" + (i + 1),
                    names[random.nextInt(names.length)],
                    "集团" + (1000 + random.nextInt(9000)),
                    "ID" + (10000 + random.nextInt(90000)),
                    outlets[random.nextInt(outlets.length)],
                    salesPoints[random.nextInt(salesPoints.length)]
            };
            tableModel.addRow(rowData);
        }
    }

    public static void addData(DefaultTableModel tableModel){
        try{
            Db db = Db.use(DSFactory.get());
            // 执行 SQL
            db.execute("CREATE TABLE IF NOT EXISTS users (id VARCHAR(100) PRIMARY KEY, name VARCHAR(100), jituan VARCHAR(100), id3 VARCHAR(100), outlets VARCHAR(100), salesPoints VARCHAR(100))");
            List<Entity> list = db.query("SELECT * FROM users");
            if(CollectionUtil.isEmpty(list)){
                generateRandomData(tableModel);
                for (int i = 0; i < tableModel.getRowCount(); i++) {
                    Object account = tableModel.getValueAt(i, 0);
                    Object name = tableModel.getValueAt(i, 1);
                    Object jituan = tableModel.getValueAt(i, 2);
                    Object id3 = tableModel.getValueAt(i, 3);
                    Object outlets = tableModel.getValueAt(i, 4);
                    Object salesPoints = tableModel.getValueAt(i, 5);
                    db.execute("INSERT INTO users (id, name, jituan, id3, outlets, salesPoints) VALUES (?,?,?,?,?,?)", account, name, jituan, id3, outlets, salesPoints);
                }
            }else{
                list.forEach(item->{
                    Object[] rowData = {
                            item.getStr("id"),
                            item.getStr("name"),
                            item.getStr("jituan"),
                            item.getStr("id3"),
                            item.getStr("outlets"),
                            item.getStr("salesPoints")
                    };
                    tableModel.addRow(rowData);
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void showDetails(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行数据！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // Create details frame
        JFrame detailsFrame = new JFrame("详情");
        detailsFrame.setSize(400, 300);
        detailsFrame.setLayout(new GridLayout(0, 1));

        String[] columnNames = {"工号", "姓名", "集团编码", "工号ID", "网点名称", "销售点编码"};
        for (int i = 0; i < columnNames.length; i++) {
            String detail = columnNames[i] + ": " + table.getModel().getValueAt(selectedRow, i);
            detailsFrame.add(new JLabel(detail));
        }

        detailsFrame.setLocationRelativeTo(null);
        detailsFrame.setVisible(true);
    }

    public static void exportDataToExcel(JTable table) {
        TableModel tableModel = table.getModel();
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择保存路径");
        int userSelection = fileChooser.showSaveDialog(null);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            String filePath = fileChooser.getSelectedFile().getAbsolutePath();
            if (!filePath.endsWith(".xlsx")) {
                filePath += ".xlsx";
            }
        }
    }
}
